import {reqcate,reqgood,reqcartadd} from "../../request/api"
import { Toast } from 'antd-mobile'
//状态
const initState ={
    cates:[],
    activeKey:0,
    goods:[]
}

//actionType
const TYPES={
    CATE_CHANGE_CATE:"CATE_CHANGE_CATE",
    CATE_CHANGE_GOODS:"CATE_CHANGE_GOODS",
    CATE_CHANGE_ACTICEKEY:"CATE_CHANGE_ACTICEKEY"
}

//修改state reducer
const reducer = (state=initState,action)=>{
    switch(action.type){
        case TYPES.CATE_CHANGE_CATE:
            return {
                ...state,
                cates:action.cates
            }
        case TYPES.CATE_CHANGE_GOODS:
            return {
                ...state,
                goods:action.goods
            }
        case TYPES.CATE_CHANGE_ACTICEKEY:
            return {
                ...state,
                activeKey:action.activeKey
            }
        default:
            return state;
    }
}

//逻辑和异步actions actionCreators
export const actions={
    changeCate:cates=>({type:TYPES.CATE_CHANGE_CATE,cates}),

    requestCates:()=>{
        return (dispatch,getState)=>{
            let cates = getCates(getState())
            if(cates.length > 0){
                return
            }
            reqcate().then(d=>{
                dispatch(actions.changeCate(d.data.list))
            })
        }
    },

    changeGoods:goods=>({type:TYPES.CATE_CHANGE_GOODS,goods}),

    requestGoods:()=>{
        return (dispatch,getState)=>{
            let goods = getGoods(getState())
            if(goods.length > 0){
                return
            }
            reqgood().then(d=>{
                dispatch(actions.changeGoods(d.data.list))
            })
        }
    },

    changeActivekey:activeKey=>({type:TYPES.CATE_CHANGE_ACTICEKEY,activeKey})
}

//导出数据 Selectors
export const getCates=(state)=>state.Cate.cates
export const getGoods=(state)=>state.Cate.goods
export const getActivekey=(state)=>state.Cate.activeKey

//展示在页面的数据
export const showGoods = state =>{
    let goods = getGoods(state)
    let activeKey= getActivekey(state)
    return goods.length ===0 ?[]: goods[activeKey].content
}

//导出reduer
export default reducer;